# -*- coding: utf-8 -*-
# @author: 龙非池
from __future__ import unicode_literals

import re

from django.core.urlresolvers import reverse
from django.views.decorators.cache import never_cache
from wenlincms.conf import settings
from wenlincms.generic.forms import ThreadedCommentForm
from wenlincms.utils.views import render, paginate

"""
本文件用于存储一些C端用公用函数
"""


# 注册时判断是否email或telephone
def isEmailOrTelephoneFormat(emailortelephone):
    """
    :param emailortelephone: 输入的字符串（电话号码或者邮件地址）
    :return:列表['you@email',None] or [None,'your,telephone'] or [None. None]
    """
    m = re.match(r'(?P<email>[^\._-][\w\.-]+@(?:[A-Za-z0-9]+\.)+[A-Za-z]+$)|(?P<telephone>^1[3458]\d{9}$)',
                 emailortelephone)
    if m:
        return m.group(1, 2)
    else:
        return [None, None]


def isEmailFormat(email):
    m = re.match(r'(?P<email>[^\._-][\w\.-]+@(?:[A-Za-z0-9]+\.)+[A-Za-z]+$)', email)
    if m:
        return m.group(1)
    else:
        return None


def set_random_code(telephone, time):
    import random
    from django.core.cache import cache
    random_code = str(random.randint(10000, 99999))
    cache.set("random_code" + telephone, random_code, time)
    random_code = [random_code, time / 60]
    return random_code


def isTelephoneFormat(telephone):
    m = re.match(r'(?P<telephone>^1[3458]\d{9}$)', telephone)
    if m:
        return m.group(1)
    else:
        return None


@never_cache
def paged_comment(request, obj):
    """
    详情页专用的评论分页函数
    """
    order = request.GET.get("order")
    if order and order in ['-submit_date', 'submit_date']:
        comments_queryset = obj.comments.all().order_by(order)
    else:
        comments_queryset = obj.comments.all().order_by('-submit_date')
    comments_queryset = paginate(comments_queryset, request.GET.get("page", 1),
                                 settings.LIST_PER_PAGE, settings.MAX_PAGING_LINKS)
    context = {"request": request, "all_comments": comments_queryset}

    form = ThreadedCommentForm(context["request"], obj)
    try:
        context["posted_comment_form"]
    except KeyError:
        context["posted_comment_form"] = form
    context["unposted_comment_form"] = form
    context["comment_url"] = reverse("comment")
    context["object_for_comments"] = obj

    try:
        replied_to = int(context["request"].POST["replied_to"])
    except KeyError:
        replied_to = 0
    context.update({
        "wlcomments_for_thread": context["all_comments"],
        "no_comments": not context["all_comments"],
        "replied_to": replied_to,
        "wlajaxid": "#comment_thread",
        "commenturl": obj.get_absolute_url() + 'comment/',
    })
    return render(request, "generic/includes/paged_comments.html", context)
